package main

import (
	"bufio"
	"log"
	"os"
	"strings"
)

var muban = `function cd[zhanwei0] --description 'alias cd[zhanwei0]=cd [zhanwei1]'
	cd [zhanwei1] $argv;
end`
var fishconfig = `/Users/newone/.config/fish/functions/`

var openmode int = os.O_CREATE | os.O_WRONLY

func main() {
	if len(os.Args) < 2 {
		log.Fatalln("specify an alias name of this directory")
		return
	}
	one := os.Args[1]
	if one == "" {
		log.Fatalln("specify an alias name of this directory")
		return
	}
	pwd, ok := os.LookupEnv("PWD")
	if !ok {
		log.Fatalln("Cant find pwd")
		return
	}
	muban = strings.Replace(muban, `[zhanwei1]`, pwd, -1)
	muban = strings.Replace(muban, `[zhanwei0]`, one, -1)
	fishpath := fishconfig + "cd" + one + ".fish"
	_, err := os.Stat(fishpath)
	if err == nil {
		log.Println("Exists !")
		{
			scanner := bufio.NewScanner(os.Stdin)
			log.Println("The file already exists, would you want to")
			log.Println("                                           REPLACE it? [y/n]")
			for scanner.Scan() {
				text := scanner.Text()
				if text != "y" && text != "n" && text != "" {
					log.Println("The file already exists, would you want to")
					log.Println("                                           REPLACE it? [y/n]")
					continue
				}
				switch text {
				case "n":
					goto l
				default:
					openmode = os.O_TRUNC | os.O_WRONLY
					goto w
				}
			}
		}
	}
	goto w
w:
	{
		f, err := os.OpenFile(fishpath, openmode, 0666)
		defer f.Close()
		if err != nil {
			log.Fatalln(err.Error())
		}
		f.WriteString(muban)
		goto l
	}
l:
	{
		return
	}
}
